package com.bjy.qa.util.security;

import com.bjy.qa.dao.user.UserDao;
import com.bjy.qa.dao.user.UserRoleDao;
import com.bjy.qa.entity.user.User;
import com.bjy.qa.entity.user.UserRole;
import com.bjy.qa.util.redis.RedisUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

/**
 * 用户详细信息
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    @Resource
    UserDao userDao;

    @Resource
    UserRoleDao userRoleDao;

    @Resource
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userDao.selectByAcount(userName);
        if (user == null) {
             throw new RuntimeException("登录失败，用户名或密码错误！");
        }

        // 设置用户角色
        List<String> roles = new LinkedList<>();
        List<UserRole> userRoles = userRoleDao.selectByUserId(user.getId());
        for (UserRole userRole : userRoles) {
            roles.add(userRole.getRole().getName());
        }
        LoginUser loginUser = new LoginUser(user, roles);

        // 将 loginUser 写入 redis
        String redisKey = "qap:login:userId:" + user.getId();
        redisUtil.set(redisKey, loginUser);

        return loginUser;
    }
}
